package pchfserver;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;

/**
 * 
 * @author 854185
 *
 */
public class HttpFileServer {
	
	public void start(String localDir){
		EventLoopGroup acceptorGroup = new NioEventLoopGroup();
		EventLoopGroup clientGroup = new NioEventLoopGroup();
		ServerBootstrap serverBootstrap = new ServerBootstrap();
		serverBootstrap.group(acceptorGroup, clientGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG,100)
		.childHandler(new ChannelInitializer<SocketChannel>() {
			protected void initChannel(SocketChannel sc){
				sc.pipeline().addLast("http-decoder", new HttpRequestDecoder());
				sc.pipeline().addLast("http-aggregator", new HttpObjectAggregator(64 * 1024));
				sc.pipeline().addLast("http-encoder", new HttpResponseEncoder());
				sc.pipeline().addLast("http-handler", new HttpRequestHandle(localDir));
			}
		});
		ChannelFuture channelFuture;
		try {
			channelFuture = serverBootstrap.bind(8080).sync();
			channelFuture.channel().closeFuture().sync();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}finally{
			acceptorGroup.shutdownGracefully();
			clientGroup.shutdownGracefully();
		}
	}
}
